<?php


namespace Beerus\Modules\BrandActivity\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel;
use Biz\cache\lottery\CActivityContent;
use Biz\model\springHomeDecActivity\ContentTopic;
use Biz\model\springHomeDecActivity\ContentTopic as mContentTopic;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;

class TopicController extends Controller
{
    const  PAGE_SIZE = 20;

    public function index(Request $request, Content $content): Content
    {
        $request_data = $request->all();
        $condition = self::getCondition($request_data);
        $page_size = $request->input("per_page", self::PAGE_SIZE);
        $page = $request->input("page", 1);
        $where = $condition;
        $where['LIMIT'] = [
            ($page - 1) * $page_size,
            $page_size,
        ];
        $list = ContentTopic::dataSelect($where);
        unset($where['LIMIT']);
        $total = ContentTopic::dataCount($where);
        $gridModel = new GridDataModel($list, $total, [
            'perPage' => $page_size,
        ]);
        $grid = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel) {
                $grid->paginate($gridModel->getPerPage());
                $grid->filter(function ($filter) {
                    // 在这里添加字段过滤器
                    $filter->column(1 / 2, function ($filter) {
                        $filter->equal('main_topic_id', '大主题ID')->placeholder('大主题ID');
                    });
                    $filter->column(1 / 2, function ($filter) {
                        $filter->equal('show_date', '展示日期')->date('Y-m-d');
                    });

                    $filter->expand();//默认展开
                });
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->disableActions();
                $grid->column('id', '主键ID');
                $grid->column('main_topic_id', '大主题ID');
                $grid->column('name', '主题')->editable();
                $grid->column('show_date', '展示日期')->editable();
                $grid->column('is_main', '大主题');
                $grid->column('is_test', '测试')->editable();
                $grid->column('weight', '排序权重')->editable();
                $grid->column('image', '主题图')->editable();
                $grid->column('create_time', '创建时间');

            });

        $tab = new Tab();
        $tab->add('活动主题列表', $grid->render(), true);
        $content->row($tab);

        return $content
            ->header('活动主题列表')
            ->description(' ')
            ->breadcrumb(['text' => '活动主题列表', 'url' => '/brandActivity/stopic']);
    }

    private static function getCondition($request): array
    {
        $condition = [];
        if (isset($request['id']) && !empty($request['id'])) {
            $condition['id'] = $request['id'];
        }
        if (isset($request['main_topic_id']) && !empty($request['main_topic_id'])) {
            $condition['main_topic_id'] = $request['main_topic_id'];
        }
        if (isset($request['show_date']) && !empty($request['show_date'])) {
            $condition['show_date'] = $request['show_date'];
        }
        return $condition;
    }

    public function create(Content $content, Form $form): Content
    {
        $date = date('Y-m-d',time());
        $mainTopic = mContentTopic::getMainTopic($date);
        $main_topic_id = empty($mainTopic['topic_id']) ? 0 : $mainTopic['topic_id'];

        $form->disableReset();
        $form->text('main_topic_id', "大主题ID")->default($main_topic_id)->required();
        $form->text('name', "主题")->required();
        $form->text('image', "主题图像");
        $form->date('show_date', "展示日期")->default(date('Y-m-d',time()))->required();
        $options1 = ['否', '是'];
        $is_main = $main_topic_id === 0 ? 1 : 0;
        $form->select('is_main', '大主题')->options($options1)->default($is_main);
        $form->select('is_test', '是否测试')->options($options1)->default(0);
        $form->text('weight', "排序")->default(0);
        $form->confirm('确定创建吗？');

        $form->action('/admin/brandActivity/stopic/save');
        return $content
            ->header('新增')
            ->description(' ')
            ->breadcrumb(
                ['text' => '活动主题列表', 'url' => '/brandActivity/stopic'],
                ['text' => '新增']
            )
            ->row($form);
    }

    public function save(Request $request)
    {
        $params = $request->all();
        $data = [
            'show_date' => $params['show_date'],
            'main_topic_id' => $params['main_topic_id'],
            'name' => $params['name'],
            'image' => $params['image'],
            'data_status' => ContentTopic::STATUS_NORMAL,
            'is_main' => $params['is_main'],
            'is_test' => $params['is_test'],
            'weight' => $params['weight'],
            'create_time' => date('Y-m-d H:i:s', time()),
            'update_time' => date('Y-m-d H:i:s', time()),
        ];
        $result = ContentTopic::dataInsert($data);
        if ($result) {
            $success = new MessageBag([
                'title' => '成功',
            ]);
            CActivityContent::delCacheTopics($data['show_date']);
        } else {
            $error = new MessageBag([
                'title' => '添加失败',
            ]);
            return back()->with(compact('error'))->withInput();
        }
        return redirect('/admin/brandActivity/stopic')->with(compact('success'));
    }

    public function editSave(Request $request, $id)
    {
        $params = $request->all();
        $name = $params['name'] ?? null;
        $value = $params['value'];
        if (!$name) {
            return response()->json([
                'message' => '操作失败',
                'status' => false,
            ]);
        }
        $data = [
            $name => $value,
            'update_time' => date('Y-m-d H:i:s', time()),
        ];
        ContentTopic::dataUpdate($data, ['id' => $id]);
        $success = [
            'message' => '操作成功',
            'status' => true,
        ];
        $show_date = ContentTopic::dataValue(['id' => $id],'show_date');
        CActivityContent::delCacheTopics($show_date);
        return response()->json($success);
    }

}